import React from 'react'
import PropTypes from 'prop-types'
import cssStyle from './index.module.css'

const context = React.createContext()

class RadioGroup extends React.PureComponent{
    onChange = value => {
        if(this.props.onChange){
            this.props.onChange(value, this.props)
        }
    }
    render(){
        let invalidStyle = {}
        if(this.props.invalid){
            invalidStyle.border = '1px solid red'
            invalidStyle.paddingLeft = '12px'
        }
        return(
            <context.Provider value={{
                onChange: this.onChange,
                value: this.props.value
            }}>
                <div style={{ borderRadius: '4px', ...invalidStyle, ...this.props.style }}>
                    { this.props.children }
                </div>
            </context.Provider>
        )
    }
}

RadioGroup.propTypes = {
    onChange: PropTypes.func,
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    invalid: PropTypes.bool,
    style: PropTypes.object
}

class Radio extends React.PureComponent{
    static contextType = context
    onClick = e => {
        e.stopPropagation()
        if (this.props.disabled) {
            return
        }
        if (this.context && this.context.onChange && this.props.value !== undefined) {
            this.context.onChange(this.props.value)
        }
        if(this.props.onChange){
            this.props.onChange()
        }
    }
    render(){
        let checked = this.props.checked
        if (this.context && this.context.value && this.props.value) {
            checked = this.props.value === this.context.value
        }
        return(
            <div className={ cssStyle.radio + (this.props.disabled ? ' ' + cssStyle.disabled : '') } style={ this.props.style || {} } onClick={ this.onClick }>
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <span className={ cssStyle.checkbox + ' ' + (checked ? cssStyle.checked : '') }>
                        <span className={ cssStyle.radioInner }></span>
                    </span>
                    <span className={ this.props.disabled ? cssStyle.disabled : '' } style={{ color: checked ? '#409eff' : '#000', marginLeft: '8px', marginRight: '12px' }}>{ this.props.label }</span>
                </div>
            </div>
        )
    }
}

Radio.propTypes = {
    onChange: PropTypes.func,
    value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    label: PropTypes.string,
    checked: PropTypes.bool,
    disabled: PropTypes.bool
}

export {
    RadioGroup,
    Radio
}